package com.atguigu.yygh.hosp.controller.api;


import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCode;
import com.atguigu.yygh.hosp.Utils.HttpRequestHelper;
import com.atguigu.yygh.hosp.Utils.MD5;
import com.atguigu.yygh.hosp.Utils.Result;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.TreeMap;

@Api(tags = "医院管理API接口")
@RestController
@RequestMapping("/api/hosp")
@Slf4j
public class ApiController {

    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private HospitalSetService hospitalSetService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private ScheduleService scheduleService;

    @ApiOperation(value = "上传医院基本信息")
    @PostMapping("saveHospital")
    public Result saveHospital(HttpServletRequest request) {
        //获取医院端的请求参数
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //传输过程中“+”转换为了" "，因此我们要转换回来
        String logoData = (String) paramMap.get("logoData");
        logoData = logoData.replaceAll(" ", "+");
        paramMap.put("logoData", logoData);

        //签名校验
        checkSign(paramMap);
        log.info("验签成功");

        //将请求参数中提交上来的数据保存到mongodb中
        hospitalService.save(paramMap);
        return Result.ok();
    }

    @ApiOperation(value = "获取医院信息")
    @PostMapping("hospital/show")
    public Result hospital(HttpServletRequest request) {
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //验签  --->  时间戳 + singkey + 随机数 + URL所有参数
        checkSign(paramMap);
        log.info("验签成功");

        String hoscode = (String) paramMap.get("hoscode");
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        return Result.ok(hospital);
    }


    @ApiOperation(value = "上传科室信息")
    @PostMapping("saveDepartment")
    public Result saveDepartment(HttpServletRequest request) {
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //签名校验
        checkSign(paramMap);
        log.info("验签成功");

        //将请求参数中提交上来的数据保存到mongodb中
        departmentService.save(paramMap);
        return Result.ok();
    }

    @ApiOperation(value = "获取科室信息")
    @PostMapping("department/list")
    public Result department(HttpServletRequest request) {
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //验签  --->  时间戳 + singkey + 随机数 + URL所有参数
        checkSign(paramMap);
        log.info("验签成功");

        //查询所有科室信息 并 进行分页
        String hoscode = (String) paramMap.get("hoscode");

        //Integer page = Integer.valueOf((String) paramMap.get("page"));
        //Integer limit = Integer.valueOf((String) paramMap.get("limit"));

        int page = StringUtils.isEmpty(paramMap.get("page")) ? 1 : Integer.parseInt((String) paramMap.get("page"));
        int limit = StringUtils.isEmpty(paramMap.get("limit")) ? 10 : Integer.parseInt((String) paramMap.get("limit"));

        //分页查询 hoscode对应的医院的列表信息
        Page<Department> pages = departmentService.selectPage(page, limit, hoscode);
        return Result.ok(pages);
    }

    @ApiOperation(value = "删除科室")
    @PostMapping("department/remove")
    public Result removeDepartment(HttpServletRequest request) {
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //验签  --->  时间戳 + singkey + 随机数 + URL所有参数
        checkSign(paramMap);
        log.info("验签成功");

        String hoscode = (String) paramMap.get("hoscode");
        String depcode = (String) paramMap.get("depcode");

        departmentService.remove(hoscode,depcode);

        return Result.ok();
    }

    @ApiOperation(value = "上传排班")
    @PostMapping("saveSchedule")
    public Result saveSchedule(HttpServletRequest request) {
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //签名校验
        checkSign(paramMap);
        log.info("验签成功");

        //将请求参数中提交上来的数据保存到mongodb中
        scheduleService.save(paramMap);
        return Result.ok();
    }

    @ApiOperation(value = "获取排班分页列表")
    @PostMapping("schedule/list")
    public Result schedule(HttpServletRequest request) {
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //验签
        checkSign(paramMap);
        log.info("验签成功");

        String hoscode = (String) paramMap.get("hoscode");
        int page = StringUtils.isEmpty(paramMap.get("page")) ? 1 : Integer.parseInt((String) paramMap.get("page"));
        int limit = StringUtils.isEmpty(paramMap.get("limit")) ? 10 : Integer.parseInt((String) paramMap.get("limit"));

        Page<Schedule> pages = scheduleService.selectPage(page,limit,hoscode);

        return Result.ok(pages);
    }

    @ApiOperation(value = "删除排班")
    @PostMapping("schedule/remove")
    public Result removeSchedule(HttpServletRequest request) {

        Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap());

        //验签
        checkSign(paramMap);
        log.info("验签成功");

        String hoscode = (String)paramMap.get("hoscode");
        String hosScheduleId = (String)paramMap.get("hosScheduleId");

        scheduleService.remove(hoscode, hosScheduleId);
        return Result.ok();
    }

        /**
         * 验签方法
         *
         * @param paramMap
         */
    public void checkSign(Map<String, Object> paramMap) {
        //获取参数中的签名
        String hospSing = (String) paramMap.get("sign");
        //获取医院编号并获取签名秘钥
        //生成签名
        String creatSign = getSign(paramMap, hospitalSetService.getSignKey((String) paramMap.get("hoscode")));
        //比较参数中的签名和生成的签名是否一致
        if (!hospSing.equals(creatSign)) {
            throw new YyghException(ResultCode.ERROR, "验签失败");
        }
    }

    /**
     * 请求数据获取签名
     *
     * @param paramMap
     * @return
     */
    private String getSign(Map<String, Object> paramMap, String signKey) {
        if (paramMap.containsKey("sign")) {
            paramMap.remove("sign");
        }
        //传输过程中的"+" 会变成"",因此要转换回来
        TreeMap<String, Object> sorted = new TreeMap<>(paramMap);
        StringBuilder str = new StringBuilder();
        for (Map.Entry<String, Object> param : sorted.entrySet()) {
            str.append(param.getValue()).append("|");
        }
        str.append(signKey);
        String md5Str = MD5.encrypt(str.toString());
        return md5Str;
    }

}